package com.dayu.store.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.dayu.common.config.RuoYiConfig;
import com.dayu.common.utils.DateUtils;
import com.dayu.common.utils.SecurityUtils;
import com.dayu.common.utils.StringUtils;
import com.dayu.common.utils.file.FileUtils;
import com.dayu.recovery.domain.RecoveryGoods;
import com.dayu.store.domain.StoreData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dayu.store.mapper.StoreCollectMapper;
import com.dayu.store.domain.StoreCollect;
import com.dayu.store.service.IStoreCollectService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 门店回收Service业务层处理
 *
 * @author HK
 * @date 2021-07-02
 */
@Service
public class StoreCollectServiceImpl implements IStoreCollectService
{
    @Resource
    private StoreCollectMapper storeCollectMapper;

    /**
     * 查询门店回收
     *
     * @param storeId 门店回收ID
     * @return 门店回收
     */
    @Override
    public StoreCollect selectStoreCollectById(Long storeId)
    {
        return storeCollectMapper.selectStoreCollectById(storeId);
    }

    @Override
    public List<Map<String, Object>> queryPriceChatData() {
        StoreCollect collect = new StoreCollect();
        List<StoreCollect> list = storeCollectMapper.selectStoreCollectList(collect);
        int k1 = 0; //1000以下
        int k2 = 0; //1000-1999
        int k3 = 0; //2000-2999
        int k4 = 0; //3000-4999
        int k5 = 0; //5000以上

        for (StoreCollect item : list) {
            if(ObjectUtils.isEmpty(item.getPrice()))
                continue;
            double a = item.getPrice().doubleValue();
            if(a < 1000)
                k1++;
            else if(a < 2000)
                k2++;
            else if(a < 3000)
                k3++;
            else if(a < 4000)
                k4++;
            else
                k5++;
        }
        List<Map<String, Object>> res = new ArrayList<>();
        res.add(createChatMap("1000以下", k1));
        res.add(createChatMap("1000-1999", k2));
        res.add(createChatMap("2000-2999", k3));
        res.add(createChatMap("3000-4999", k4));
        res.add(createChatMap("5000以上", k5));

        return res;
    }

    private Map<String, Object> createChatMap(String name, Object value) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("value", value);
        return map;
    }

    @Override
    public Map<String, Object> queryAvgUseTimeList() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> useTime = storeCollectMapper.queryAvgUseTimeList();
        List<Map<String, Object>> offerName = storeCollectMapper.queryOfferNameCountList();
        Integer collect = storeCollectMapper.queryCollectNumber();
        Integer rk = storeCollectMapper.queryNowCreateNumber();
        Double salePrice = storeCollectMapper.queryNowSaleNumber();
        Double avgCost = storeCollectMapper.queryAvgCostPrice();
        Integer stockNum = storeCollectMapper.queryStockTotalNumber();
        String saleAndNum = storeCollectMapper.queryNowSaleAndTotalNumber();
        Integer jjcl = storeCollectMapper.queryWarehouseNumber();
        String collectPrice = storeCollectMapper.queryCollectAndPrice();
        map.put("useTime", useTime);
        map.put("offerName", offerName);
        map.put("collect", collect);
        map.put("rk", rk);
        map.put("salePrice", salePrice);
        map.put("avgCost", avgCost);
        map.put("stockNum", stockNum);
        map.put("saleAndNum", saleAndNum);
        map.put("jjcl", jjcl);
        map.put("collectPrice", collectPrice);
        return map;
    }

    /**
     * 查询门店回收列表
     *
     * @param storeCollect 门店回收
     * @return 门店回收
     */
    @Override
    public List<StoreCollect> selectStoreCollectList(StoreCollect storeCollect)
    {
        return storeCollectMapper.selectStoreCollectList(storeCollect);
    }

    /**
     * 新增门店回收
     *
     * @param storeCollect 门店回收
     * @return 结果
     */
    @Override
    public int insertStoreCollect(StoreCollect storeCollect)
    {
        storeCollect.setStatus(3); //待收货
        storeCollect.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        storeCollect.setCreateTime(DateUtils.getNowDate());
        return storeCollectMapper.insertStoreCollect(storeCollect);
    }

    @Override
    @Transactional
    public int insertList(List<StoreCollect> list) {
        int num = 0;
        for (StoreCollect collect : list) {
            num += insertStoreCollect(collect);
        }
        return num;
    }

    /**
     * 修改门店回收
     *
     * @param storeCollect 门店回收
     * @return 结果
     */
    @Override
    public int updateStoreCollect(StoreCollect storeCollect)
    {
        return storeCollectMapper.updateStoreCollect(storeCollect);
    }

    /**
     * 批量审核，单条循环修改
     * @param ids
     * @return
     */
    public int auditList(Long[] ids) {
        int nums = 0;
        List<StoreCollect> list = selectStoreCollectByIds(ids);
        for(StoreCollect collect : list) {
            if(collect.getBillStatus() != 1) {
                continue;
            }
            collect.setBillStatus(2); //已审核
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            collect.setCheckInfo(SecurityUtils.getLoginUser().getUser().getNickName() +"_"+ dateFormat.format(new Date()));
            nums += updateStoreCollect(collect);
        }
        return nums;
    }

    /**
     * 批量删除门店回收
     *
     * @param storeIds 需要删除的门店回收ID
     * @return 结果
     */
    @Override
    public int deleteStoreCollectByIds(Long[] storeIds)
    {
        return storeCollectMapper.deleteStoreCollectByIds(storeIds);
    }

    /**
     * 删除门店回收信息
     *
     * @param storeId 门店回收ID
     * @return 结果
     */
    @Override
    public int deleteStoreCollectById(Long storeId)
    {
        return storeCollectMapper.deleteStoreCollectById(storeId);
    }

    /**
     * 批量新增
     * @param num
     * @return
     */
    @Override
    public int insertStoreCollectList(Integer num) {
        List<StoreCollect> list = new ArrayList<>();
        for(int i = 0; i < num; i++) {
            StoreCollect collect = new StoreCollect();
            collect.setStatus(1);
            list.add(collect);
        }
        return storeCollectMapper.insertStoreCollectList(list);
    }

    /**
     * 实时数据统计
     * @param storeCollect
     * @return
     */
    @Override
    public List<StoreData> selectStoreDataList(StoreCollect storeCollect) {
        List<StoreData> list = storeCollectMapper.selectStoreDataList(storeCollect);
        if(storeCollect.getParams() != null){
            Map<String, Object> map = storeCollect.getParams();
            String time = map.get("startTime") != null ? map.get("startTime").toString() : "";
            time += " 至 " + (map.get("endTime") != null ? map.get("endTime").toString() : "");
            for(StoreData storeData: list) {
                storeData.setDataTime(time);
            }
        }
        return list;
    }

    /**
     * 报价师 报价数据统计
     * @param storeCollect
     * @return
     */
    @Override
    public List<Map<String, Object>> offerDataList(StoreCollect storeCollect) {
        //如果筛选条件为空，则默认筛选当日数据
        if(storeCollect.getParams() == null || storeCollect.getParams().get("offerStartTime") == null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("offerStartTime", dateFormat.format(new Date()));
            storeCollect.setParams(paramsMap);
        }
        //获取指定报价时间报价数据
        List<StoreCollect> list = selectStoreCollectList(storeCollect);
        List<Map<String, Object>> respList = new ArrayList<>();
        for(StoreCollect collect: list) {
            //报价师为空，跳过此数据
            if(StringUtils.isEmpty(collect.getOfferName())) {
                continue;
            }
            //是否新增开关
            boolean bool = true;
            //循环判断此条数据是否属于已有
            for(Map<String, Object> map: respList) {
                if(collect.getOfferName().equals(map.get("offerName"))) {
                    bool = false;
                    boolean twoBool = true;
                    for(Map<String, Object> mapTwo: (List<Map<String, Object>>) map.get("dataList")) {
                        if(collect.getCompanyInfo().split(" ")[0].equals(mapTwo.get("supplierName"))){
                            twoBool = false;
                            mapTwo.put("number", ((Integer) mapTwo.get("number") + 1));
                            mapTwo.put("price", collect.getPrice().add((BigDecimal) mapTwo.get("price")));
                            break;
                        }
                    }
                    if(twoBool) {
                        Map<String, Object> addMap = new HashMap<>();
                        addMap.put("supplierName", collect.getCompanyInfo().split(" ")[0]);
                        addMap.put("number", 1);
                        addMap.put("price", collect.getPrice());
                        ((List<Map<String, Object>>) map.get("dataList")).add(addMap);
                    }
                }
            }
            //都不存在，新增
            if(bool) {
                Map<String, Object> parentMap = new HashMap<>();
                List<Map<String, Object>> dataList = new ArrayList<>();
                //外列表
                parentMap.put("offerName", collect.getOfferName());
                parentMap.put("dataList", dataList);

                //子列表
                Map<String, Object> childrenMap = new HashMap<>();
                childrenMap.put("supplierName", collect.getCompanyInfo().split(" ")[0]);
                childrenMap.put("number", 1);
                childrenMap.put("price", collect.getPrice());
                dataList.add(childrenMap);
                respList.add(parentMap);
            }
        }
        return respList;
    }

    /**
     * 批量修改回收数据状态
     * @param storeIds 编号ids
     * @return
     */
    @Override
    public int updateStoreCollectByList(Long[] storeIds) {
        List<StoreCollect> list = selectStoreCollectByIds(storeIds);
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
        Date newDate = new Date();
        String str = SecurityUtils.getLoginUser().getUser().getNickName() + "(生成回收)_" + sdf.format(newDate);
        for(StoreCollect collect : list) {
            collect.setStatus(4); //已收货
            if(collect.getCollectInfo() == null ) {
                collect.setCollectInfo(str);
                collect.setCollectTime(newDate);
            }else {
                collect.setCollectInfo(collect.getCollectInfo() + " > " + str);
            }
        }
        return storeCollectMapper.updateStoreCollectByList(list);
    }

    /**
     * 根据ids查询列表
     * @param storeIds
     * @return
     */
    @Override
    public List<StoreCollect> selectStoreCollectByIds(Long[] storeIds) {
        return storeCollectMapper.selectStoreCollectByIds(storeIds);
    }

    @Override
    public int updateHayPay(Long storeId) {
        StoreCollect storeCollect = new StoreCollect();
        storeCollect.setStoreId(storeId);
        storeCollect.setHasPay(2);

        int num = storeCollectMapper.updateStoreCollect(storeCollect);
        //删除收款码
        if(num > 0) {
            StoreCollect sel = storeCollectMapper.selectStoreCollectById(storeId);
            if(!ObjectUtils.isEmpty(sel)) {
                if(StringUtils.isNotEmpty(sel.getPayScan())) {
                    String path = sel.getPayScan().replace("/profile","");
                    path = RuoYiConfig.getProfile() + path;
                    FileUtils.deleteFile(path);
                }
            }
        }
        return num;
    }
}
